package com.cskaoyan.controller.admin;

import com.cskaoyan.annotation.LogAddAnnotation;
import com.cskaoyan.bean.common.BaseRespVo;
import com.cskaoyan.bean.po.AdminInfoBean;
import com.cskaoyan.bean.po.InfoData;
import com.cskaoyan.bean.po.LoginUserData;
import com.cskaoyan.bean.po.MarketAdmin;
import com.cskaoyan.config.shiro.CustomToken;
import com.cskaoyan.service.AuthService;
import com.cskaoyan.util.Md5Util;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Map;

//shiro整合之后，在做具体的开发
//响应结果都是JSON，Controller组件上我们都用@RestController注解
@RestController
@RequestMapping("admin/auth")
public class AuthController {
    @Autowired
    AuthService authService;

    /**
     * Shiro安全框架 → 视频课程 4个课时 → 认证（登录）
     * 如果参数比较少，类型比较简单的话，使用map来接收也可以
     */
    @LogAddAnnotation
    @PostMapping("login")
    public BaseRespVo<LoginUserData> login(@RequestBody Map map) {
        String username = (String) map.get("username");
        String password = (String) map.get("password");

        // 写业务
        // todo:获取subject，只能作为局部变量，不同用户是不同主体
        Subject subject = SecurityUtils.getSubject();
        // 进行登录认证，传入登录时的username、password
        // UsernamePasswordToken token = new UsernamePasswordToken(username,password);
        String md5 = Md5Util.getMd5(password, "crazy");
        CustomToken customToken = new CustomToken(username, md5, "webLogin");
        try {
            // 会执行到Realm.doGetAuthenticationInfo()
            subject.login(customToken);
        } catch (AuthenticationException e) {
            e.printStackTrace();
        }
        // 判断登录认证是否成功，不成功返回认证失败
        boolean authenticated = subject.isAuthenticated();
        if (!authenticated) {
            return BaseRespVo.invalidParameter("认证失败，账号密码错误！");
        }
        // todo:获取session，用于获取sessionId响应给前端
        Session session = subject.getSession();
        // todo:获取第一个Principal参数，是当前登录的用户对象
        MarketAdmin principal = (MarketAdmin) subject.getPrincipals().getPrimaryPrincipal();

        LoginUserData loginUserData = new LoginUserData();
        AdminInfoBean adminInfo = new AdminInfoBean();
        // adminInfo.setAvatar("https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
        // adminInfo.setNickName("admin123");
        // loginUserData.setAdminInfo(adminInfo);
        // loginUserData.setToken("c4d988f3-e4c5-4e46-b6ce-13b9e008ea20");

        adminInfo.setAvatar(principal.getAvatar());
        adminInfo.setNickName(principal.getUsername());
        loginUserData.setAdminInfo(adminInfo);
        // 返回sessionId给前端，前端请求头Cookie携带sessionId，sessionManage回话管理
        loginUserData.setToken((String) session.getId());
        return BaseRespVo.ok(loginUserData);
    }


    @RequestMapping("info")
    public BaseRespVo info(String token) {
        Subject subject = SecurityUtils.getSubject();
        PrincipalCollection principals = subject.getPrincipals();
        if (principals == null) {
            return BaseRespVo.invalidParameter("登录状态异常，请重新登录");
        }
        MarketAdmin marketAdmin = (MarketAdmin) principals.getPrimaryPrincipal();
        InfoData infoData = authService.info(marketAdmin);

        // //开发完shiro之后，再整合
        // InfoData infoData = new InfoData();
        // infoData.setName("admin123");
        //
        // //根据primaryPrincipal做查询
        // infoData.setAvatar("https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
        // ArrayList<String> roles = new ArrayList<>();
        // roles.add("超级管理员");
        // infoData.setRoles(roles);
        // ArrayList<String> perms = new ArrayList<>();
        // perms.add("*");
        // infoData.setPerms(perms);

        return BaseRespVo.ok(infoData);
    }

    @LogAddAnnotation
    @RequestMapping("logout")
    public BaseRespVo logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return BaseRespVo.ok();
    }

    @RequestMapping("noAuthc")
    public BaseRespVo noAuthc() {
        return BaseRespVo.unAuthc();
    }


}
